import { reqShopCartList, reqDeleteShopCart, reqUpdateShopCart } from '@/api'
const state = {
    cartList: [],
}

const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList
    }
}

const actions = {
    async getCartList({ commit }) {
        const res = await reqShopCartList()
        console.log(res)
        commit('GETCARTLIST', res.data)
    },
    async deleteCart({ commit }, skuId) {
        const res = await reqDeleteShopCart(skuId)
        if (res.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    async updateCart({ commit }, { skuId, isChecked }) {
        const res = await reqUpdateShopCart(skuId, isChecked);
        if (res.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    deleteAllCart({ dispatch, getters }) {
        // context相当于一个小仓库
        // console.log(context)
        let promiseArr = [];
        getters.cartData.cartInfoList.forEach(item => {
            let res = item.isChecked == 1 ? dispatch('deleteCart', item.skuId) : '';
            promiseArr.push(res);
        })
        // 如果有一个失败就失败，都为成功才成功
        return Promise.all(promiseArr);
    },
    updateAllIsChecked({ state, dispatch }, isChecked) {
        let promiseArr = [];
        state.cartList[0].cartInfoList.forEach(item => {
            let res = dispatch('updateCart', { skuId: item.skuId, isChecked: isChecked })
            promiseArr.push(res)
        })
        return Promise.all(promiseArr)
    }
}

const getters = {
    cartData() {
        return state.cartList[0] || {};
    }
}

export default {
    state,
    mutations,
    actions,
    getters,
}